package pfc.pfcjoc.entities;

// import static playn.core.PlayN.log;

import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.Fixture;
import org.jbox2d.dynamics.FixtureDef;
import org.jbox2d.dynamics.World;

import pfc.pfcjoc.core.pfcjoc;
import playn.core.GroupLayer;

public class WoodBlock extends PhysicElement {
  public static String name = "woodblock";

  public static final float MAX_SPEED = 2;
  public final float MAX_DISTANCE = 4;
  private float startX;
  private boolean movingRight = false;


  // public Block() {
  //
  // }

  public WoodBlock(final World world, final GroupLayer worldLayer, final Vec2 pos) {
    super(world, worldLayer, pos);
    setDepth(10);
    initPhysics(world, pos);
  }


  public void initPhysics(World world, Vec2 pos) {
    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyType.KINEMATIC;
    bodyDef.position = pos;
    body = world.createBody(bodyDef);
    PolygonShape polygonShape = new PolygonShape();
    float w = pfcjoc.toPhy(getWidth());
    float h = pfcjoc.toPhy(getHeight());
    polygonShape.setAsBox(w / 2f, h / 2f);

    // FixtureDef fixtureDefWoodBlock = new FixtureDef();
    // fixtureDefWoodBlock.friction = 3.0f;
    // fixtureDefWoodBlock.shape = polygonShape;

    // Fixture woodBlockFxtFixture = body.createFixture(fixtureDefWoodBlock);

    Fixture woodBlockFxtFixture = body.createFixture(polygonShape, 0);
    woodBlockFxtFixture.setUserData("woodBlockFxt");

    setPosPhy(pos); // BLOCK
    // setPosPhy(pfcjoc.toPhy(pos)); BUSH

    // Útil per gestió de colisions
    body.setUserData(this);

    // Posició inicial plataforma
    startX = pos.x;
  }


  public void paint(float alpha) {
    super.paint(alpha);
    // sprite.setSprite(spriteIndex);
  }


  public void update(float delta) {
    super.update(delta);

    if (body.getPosition().x >= startX + MAX_DISTANCE || body.getPosition().x <= startX - MAX_DISTANCE) {
      changeDirection();
    }
    if (movingRight) {
      body.setLinearVelocity(new Vec2(MAX_SPEED, body.getLinearVelocity().y));
    }
    else {
      body.setLinearVelocity(new Vec2(-MAX_SPEED, body.getLinearVelocity().y));
    }
  }


  public void changeDirection() {
    movingRight = !movingRight;
  }


  public boolean isMovingRight() {
    return movingRight;
  }


  public String getName() {
    return name;
  }


  @Override
  public float getWidth() {
    return 96;
  }


  @Override
  public float getHeight() {
    return 32;
  }


  @Override
  protected int getFirstSprite() {
    return 0;
  }


  @Override
  protected String getImagePath() {
    return "images/woodblock.png";
  }


  @Override
  protected String getJsonPath() {
    return "images/woodblock.json";
  }
}
